/*
 *  logger4cpp - Simple C++ Logger
 *
 *  Copyright (C) 2011 CodeFutures Corporation. All rights reserved.
 */

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <map>

#include "LoggerFactory.h"
#include "Logger.h"

namespace logger4cpp {

/*static*/ std::map<string,Logger*> LoggerFactory::loggerMap;

LoggerFactory::LoggerFactory() {
	isConfigured = false;
}

LoggerFactory::~LoggerFactory() {
}

void LoggerFactory::configure() {

	//TODO: should add mutex here

	if (isConfigured) {
		return;
	}

	const char *filename = getenv("LOGGER_PROPERTIES");
	if (filename==NULL) {
		filename = "/etc/log.properties";
	}

	string line;
	ifstream myfile(filename);
	if (myfile.is_open()) {
		while (! myfile.eof()) {
			getline (myfile,line);

			if (line.size() == 0 || line[0] == '#' || line[0] == ' ' || line[0] == '\t') {
				// ignore - comment or blank line
				continue;
			}

			// look for '='
			int pos = line.find('=');
			if (pos<=0) {
				// ignore, not valid
				continue;
			}

			string className = line.substr(0,pos);
			string levelName = line.substr(pos+1);

#ifdef DEBUG_LOGGER
			cerr << "Configuring Loggers from file " << filename << ": Class=" << className << "; Level=" << levelName << endl;
#endif

			// default to INFO
			int level = LOG_LEVEL_INFO;

			if (levelName == "TRACE") {
				level = LOG_LEVEL_TRACE;
			}
			else if (levelName == "DEBUG") {
				level = LOG_LEVEL_DEBUG;
			}
			else if (levelName == "INFO") {
				level = LOG_LEVEL_INFO;
			}
			else if (levelName == "WARN") {
				level = LOG_LEVEL_WARN;
			}
			else if (levelName == "ERROR") {
				level = LOG_LEVEL_ERROR;
			}

			loggerMap[className] = new Logger(className, level);

		}
		myfile.close();
	}
	else {
		// use default settings
	}

	isConfigured = true;
}

/*static*/ Logger* LoggerFactory::getLogger(string name) {
	//TODO: should add mutex here
	Logger *logger = loggerMap[name];
	if (logger==NULL) {
		logger = new Logger(name, LOG_LEVEL_INFO);
		loggerMap[name] = logger;
	}
	return logger;
}

} // namespace



